﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace OMDRun
{
    public class MainExecute
    {

         private static MainExecute _instance = null;
         public static MainExecute Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new MainExecute();
                }
                return _instance;
            }

        }

        /// <summary>
        /// 日志接口
        /// </summary>
        private log4net.ILog logger = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        //public bool DoAction(string[] lines)
        //{

        //   // string sql = "select  Project from (\r\nselect MAX(ServerTime) as ServerTime,Project  from   [dbo].[T_KanBanSublineDataByHour]\r\nwhere ServerTime > DATEADD(DAY,-3,GETDATE()) and Project like '%SFC%'\r\ngroup by  Project \r\n--order by 1\r\n) tt where  ServerTime < DATEADD(MINUTE,-30,GETDATE())";

        //   //var  list= DapperBase.GetInstance(Class_Config.KanBanServer).Query<string>(sql)?.ToList();

        //   // if (list==null || list.Count==0)
        //   // {
        //   //     return true;
        //   // }
        //     string sql = "";
        //    List<Task> taskList = new List<Task>();
           
        //     foreach (var item in lines)
        //    {
        //         sql = $" select top 1  Attbute6 from T_DataBaseCfg_Report with(nolock) where DBName = '{item}' and IsActive = 1";

        //        var  obj=  DapperBase.GetInstance(Class_Config.CentralDatabase).ExecuteScalar(sql);
        //        if (obj != null)
        //        {
        //            Task task = new Task(() =>
        //            {


        //                try
        //                {
        //                    DapperBase.GetInstance(obj.ToString()).Execute("exec  P_GetKanBanSublineDataByHour \r\nexec  P_GetKanBanLineDataByHour");
        //                }
        //                catch (Exception ex)
        //                {

        //                    logger.Error(ex);
        //                }
        //            }); 
        //            taskList.Add(task);
        //            task.Start();
        //        }
        //    }



        //    string sql1 = "select  Project from (\r\nselect MAX(ServerTime) as ServerTime,Project  from   [dbo].[T_KanBanLineDataByHour]\r\nwhere ServerTime > DATEADD(DAY,-3,GETDATE()) and Project like '%SFC%'\r\ngroup by  Project \r\n--order by 1\r\n) tt where  ServerTime < DATEADD(HOUR,-30,GETDATE())";

        //    var list1 = DapperBase.GetInstance(Class_Config.KanBanServer).Query<string>(sql1)?.ToList();
        //    if (list1 != null)
        //    foreach (var item in list1)
        //    { 
        //        sql = $" select top 1  Attbute6 from T_DataBaseCfg_Report with(nolock) where DBName = '{item.Trim()}' and IsActive = 1";

        //        var obj = DapperBase.GetInstance(Class_Config.CentralDatabase).ExecuteScalar(sql);
        //        if (obj != null)
        //        {
        //            Task task = new Task(() =>
        //            {


        //                try
        //                {
        //                    DapperBase.GetInstance(obj.ToString()).Execute("exec  P_GetKanBanLineDataByHour");
        //                }
        //                catch (Exception ex)
        //                {

        //                    logger.Error(ex);
        //                }
        //            });
        //            taskList.Add(task);
        //            task.Start();
        //        }
        //    }
        //    Task.WaitAll(taskList.ToArray());
        //    return true;
        //}





        public bool DoActionLine(string[] lines ,string procName= "P_GetKanBanLineDataByHour" ,Action<Task> actiontask=null )
        {

            string sql = "";

            List<Task> taskList = new List<Task>();
  
             
                foreach (var item in lines)
                {
                sql = $" select top 1  Attbute6 from T_DataBaseCfg_Report with(nolock) where DBName = '{item.Trim()}' and IsActive = 1";

                var obj = DapperBase.GetInstance(Class_Config.CentralDatabase).ExecuteScalar(sql);
                if (obj != null)
                {
                    Task task = new Task(() =>
                    {


                        try
                        {
                            LogHelper.LogDebug($"开始执行{item}_{procName}");
                            DapperBase.GetInstance(obj.ToString()).Execute($"exec  {procName}");
                            LogHelper.LogDebug($"执行完成{item}_{procName}");
                        }
                        catch (Exception ex)
                        {

                            LogHelper.LogError(ex.Message);
                        }
                    });
                    taskList.Add(task);
                    task.Start();
                }

                //Task task = new Task(() =>
                //    {
                //        Thread.Sleep(3000);

                //    });
                //taskList.Add(task);
                // task.Start();
            }
            //Task.WaitAll(taskList.ToArray());
            Task.WhenAll(taskList.ToArray()).ContinueWith(actiontask);
            return true;
        }



        public Task TaskAutoRun(string dbName, string [] procName)
        {
 
            string sql = "";
                sql = $" select top 1  Attbute6 from T_DataBaseCfg_Report with(nolock) where DBName = '{dbName}' and IsActive = 1";

                var obj = DapperBase.GetInstance(Class_Config.CentralDatabase).ExecuteScalar(sql);
                if (obj != null)
                {
           
                Task task = new Task(() =>
                    {
                        try
                        {
                            foreach (var item in procName)
                            {
                                LogHelper.LogDebug($"开始{dbName}_{item}执行");
                                DapperBase.GetInstance(obj.ToString()).Execute($"exec  {item}");
                                LogHelper.LogDebug($"执行{dbName}_{item}完成");
                            }
                        
                        }
                        catch (Exception ex)
                        {

                            LogHelper.LogError(ex.Message);
                        }
                    });
                    task.Start();
                    return task;
                }
                return null;
            }




            CancellationTokenSource cts = new CancellationTokenSource();



        public bool AutoStart(string[] lines )
        {
            cts=new CancellationTokenSource();
            Task.Run(() =>
            {
                bool isFirst = true;
                while (!cts.IsCancellationRequested)
                {
                   
                    if ( DateTime.Now.Minute == 0 && DateTime.Now.Second == 0|| isFirst)
                    { 
                         isFirst = false;
                        LogHelper.LogDebug("开始执行自动任务");
                        List<Task> taskList = new List<Task>();
                        foreach (var dbName in lines)
                        {
                             
                            var task = TaskAutoRun(dbName, new string[] { "P_GetKanBanSublineDataByHour", "P_GetKanBanSublineData", "P_GetKanBanLineData", "P_GetKanBanStationYield", "P_GetKanBanSectionWipData" });
                            taskList.Add(task);
                             
                        }
                        Task.WaitAll(taskList.ToArray());
                        LogHelper.LogDebug("结束执行自动任务");
                    }
                   Thread.Sleep(500);
                }
            }, cts.Token);
            return true;    
 
        }


        public void AutoStop()
        {
            if (cts != null)    
            cts.Cancel();
        }


        public bool UpdateDBSTATISTICS(string[] lines)
        { 
        

            string sql = "";
            List<Task> taskList = new List<Task>();
            foreach (var item in lines)
            {
                sql = $" select top 1  ConnectionString from T_DataBaseCfg with(nolock) where DBName = '{item}' and IsActive = 1";

                var obj = DapperBase.GetInstance(Class_Config.CentralDatabase).ExecuteScalar(sql);
                if (obj != null)
                {
                    Task task = new Task(() =>
                    {
                        try
                        {
                            string sql2 = $" declare @tempTable as table   (   TableName varchar(50)   )      \r\ninsert into @tempTable    \r\nselect distinct(tableName) from(  select  inputTable as tableName from[10.2.128.220].[SFCEKanBan].[dbo].T_KanbanSectionConfig where Flag = 1 and ProjectName = db_name()  \r\nunion all  select  outputTable as tableName from[10.2.128.220].[SFCEKanBan].[dbo].T_KanbanSectionConfig where Flag = 1 and ProjectName = db_name()  ) tt   \r\ndeclare @sql nvarchar(max)   \r\nwhile (select COUNT(1) from @tempTable) > 0  \r\nbegin  declare @TableName varchar(50)  \r\n\r\nselect top  1 @TableName = TableName from @tempTable order by TableName  print(@TableName) \r\n\r\nif OBJECT_ID(@TableName, 'U') IS NOT NULL\r\nbegin\r\nset @sql = 'UPDATE STATISTICS ' + @TableName + ' IX_' + @TableName + '_ServerTime;'  \r\nexec(@sql)  \r\nend\r\nprint(@sql)  \r\ndelete from  @tempTable where  TableName = @TableName\r\nend  ";

                            DapperBase.GetInstance(obj.ToString()).Execute(sql2, 20);
                            logger.Info($"更新{item}统计信息完成");
                        }
                        catch (Exception ex)
                        {
                            LogHelper.LogError(ex.Message);
                        }
                    });
                    taskList.Add(task);
                    task.Start();
                }
            }

            Task.WaitAll(taskList.ToArray());
            return true;

        }
    }
}
